<template>
	<view class="content uni-flex-column" :style="bgStyle">
		<CustomNavBar class="navbar">
			<template v-slot:left>
				<view class="back uni-flex uni-align-center uni-justify-center" @click="goBack">
					<uni-icons type="left" size="20"></uni-icons>
				</view>
			</template>
		</CustomNavBar>

		<view class="center">
			<view class="uni-flex top">

				<view class="uni-flex-column" style="flex: 1">
					<view class="uni-flex uni-justify-between">
						<view class="title">{{detail.serviceInfo?.name}}</view>

					</view>
					<view class="box2">
						<text class="text1">雇主需求：</text>

						<view v-if="detail.serviceInfo?.labelNames && detail.serviceInfo.labelNames.length > 0"
							v-for="(item, index) in detail.serviceInfo.labelNames" :key="index" class="item">
							<text>{{ item }}</text>
						</view>

						<view v-else>
							<text>--</text>
						</view>
					</view>
					<view class="line1">
						<text class="text1">服务内容：</text>
						<text class="content-text">{{detail.serviceInfo?.content}}</text>
					</view>
					<view class="line1">
						<text class="text1">服务时间：</text>
						<text
							class="text1">{{formatDate(detail.serviceInfo?.startTime)}}至{{formatDate(detail.serviceInfo?.endTime)}}</text>
					</view>
					<view class="line1">
						<text class="text1">服务预算：</text>
						<text class="text1">{{detail.serviceInfo?.price}}</text>
					</view>
					<view class="line1">
						<text class="text1">用工人数：</text>
						<text class="text1">{{detail.serviceInfo?.peopleNumber}}</text>
					</view>
					<view class="line2 uni-justify-between uni-align-center" @click="openMap">
						<view>
							<text class="text1">服务地址：</text>
							<text class="text1">{{detail.serviceInfo?.address}}</text>
						</view>
						<view class="distance">
							<image :src="`${$ImgBaseUrl}detail_location.png`" mode="widthFix" />
							<text class="text2">{{detail.serviceInfo?.distance}}km</text>
						</view>
					</view>
					<view class="order-map" @click="openMap">
						<!-- 地图容器 -->
						<map id="map" :latitude="Number(detail.serviceInfo?.lat)"
							:longitude="Number(detail.serviceInfo?.lng)" :scale="15" class="map-container" show-location
							:enable-scroll="true" :markers="[{
										
										latitude: Number(detail.serviceInfo?.lat),
										longitude: Number(detail.serviceInfo?.lng),
										width: 25,  // 标记点宽度（rpx）
										height: 33,  // 标记点高度（rpx）
										iconPath: `${$ImgBaseUrl}findJobDetail-position.png` 
									}]" @tap="handleMapTap" />
					</view>
					<view class="uni-flex uni-justify-center icon-box-margin">
						<view class="icon-content">
							<view class="icon-box" @click='collectHandle(titleWithDefault)'>

								<image :src="`${$ImgBaseUrl}detail_collect.png`" v-if="!titleWithDefault.contact"
									mode="widthFix" class="icon" />
								<image :src="`${$ImgBaseUrl}lookforsb-collect-selected.png`"
									v-if="titleWithDefault.contact" mode="widthFix" class="icon" />
								<text class="icon-box-text">收藏</text>
							</view>
							<view class="icon-box" @click="shareToggle">
								<image :src="`${$ImgBaseUrl}detail_share.png`" class="icon" />
								<text class="icon-box-text">分享</text>

							</view>
							<view class="icon-box" @click="goReport(detail)">
								<image :src="`${$ImgBaseUrl}detail_report.png`" class="icon" />
								<text class="icon-box-text">举报</text>

							</view>
						</view>

					</view>

				</view>
			</view>
			<view class="demand demand2" v-if="detail.userInfo!==null||detail?.userInfo">
				<view class="avatar-box">
					<image
						:src="detail?.userInfo?.avatar===''||detail?.userInfo?.avatar===null?`${$ImgBaseUrl}banner.png`:detail?.userInfo?.avatar"
						class="photo" />
				</view>
				<view class="demand2-box">
					<view class="name">
						{{detail.userInfo?.userName}}
					</view>
					<view class="rate">
						<text class="text1">结单率:</text>
						<text class="value1">{{detail.userInfo?.closeRate}}%</text>
					</view>
					<view class="box1">
						<text class="text2">共发布</text>
						<text class="value2">{{detail.userInfo?.totalCount}}单</text>
						<text class="text2 left">完成</text>
						<text class="value2">{{detail.userInfo?.endCount}}单</text>
						<text class="text2 left">近期发布</text>
						<text class="value2">{{detail.userInfo?.nearCount}}单</text>
					</view>

					<view class="box3">
						<image :src="`${$ImgBaseUrl}detail_browse.png`" mode="widthFix" class="detail_browse" />
						<text>已被{{detail.userInfo?.watchCount}}人查看</text>
						<image :src="`${$ImgBaseUrl}detail_phone.png`" mode="widthFix" class="detail_phone" />
						<text>已被{{detail.userInfo?.contactCount}}人联系</text>
					</view>
				</view>
			</view>

			<view class="demand" v-if="detail.serviceNotice!==null||detail?.serviceNotice">
				<view class="title uni-flex">
					<image :src="`${$ImgBaseUrl}detail_label.png`" mode="widthFix" />
					<text>服务须知</text>
					<image :src="`${$ImgBaseUrl}detail_label.png`" mode="widthFix" />
				</view>
				<view class="demand_content">{{ detail.serviceNotice }}</view>
			</view>

			<view class="demand" v-if="Array.isArray(detail.busServiceResults) && detail.busServiceResults.length > 0">
				<view class="title uni-flex">
					<image :src="`${$ImgBaseUrl}detail_label.png`" mode="widthFix" />
					<text>附近有活</text>
					<image :src="`${$ImgBaseUrl}detail_label.png`" mode="widthFix" />
				</view>
				<view class="job-item" v-for="(item, index) in displayedRecommendations" :key="index">
					<view class="uni-flex uni-justify-between box1">
						<view class="uni-flex uni-align-center">
							<image :src="item?.titleImage" class="photo" />
							<text class="text1">{{item?.name}}</text>
						</view>
						<view class="distance">
							<image :src="`${$ImgBaseUrl}detail_location.png`" mode="widthFix" />
							<text class="text2">{{item.distance}}km</text>
						</view>
					</view>
					<view class="line1 uni-flex uni-align-center">
						<text class="text1">雇主需求：</text>
						<view v-if="Array.isArray(item?.labelNames) && item.labelNames.length > 0"
							v-for="(item, index) in item.labelNames" :key="index" class="item">
							<text>{{ item }}</text>
						</view>
						<view v-else>
							<text>--</text>
						</view>
					</view>
					<view class="line1">
						<text class="text1">服务内容：</text>
						<text class="content-text">{{item.content}}</text>
					</view>
					<view class="line1" v-if="item?.startTime!==null&&item?.endTime!==null">
						<text class="text1">服务时间：</text>
						<text>{{item.startTime}}至{{item.endTime}}</text>
					</view>
					<view class="line1">
						<text class="text1">服务预算：</text>
						<text>{{item.price}}</text>
					</view>
					<view class="line1">
						<text class="text1">服务人数：</text>
						<text>{{ item.peopleNumber }}</text>
					</view>
					<view class="line1 uni-justify-between uni-align-center">
						<text class="text1">服务地点：</text>
						<text>{{ item.address }}</text>
					</view>
				</view>

				<view v-if="detail.busServiceResults && detail.busServiceResults.length > 2" class="view-more-btn"
					@click="toggleShowMore">
					<text>{{ showMore ? '收起' : '查看更多' }}</text>
					<uni-icons :type="showMore ? 'arrowup' : 'arrowright'" size="16" color="#999999"
						class="more-icon"></uni-icons>
				</view>
			</view>
		</view>

		<view class="footer">
			<view class="uni-flex-column box3" @tap="sendCard" v-if="currentUserInfo.userType!=='GENERAL_USER'">
				<image :src="`${$ImgBaseUrl}details_info.png`" class="icon" mode="widthFix" />
				<text class="text1">推荐名片</text>
			</view>
			<view class="btn" @click="contactEmployer">联系雇主</view>
		</view>
		<CallDialog :showDialog="showCallDialog" :phoneNumber="phoneNumber" @close="showCallDialog = false">
		</CallDialog>
		<!-- 分享弹窗 -->
		<SharePopup ref="sharePopup" :shareData="shareData" @close="handleShareClose" />

	</view>

</template>

<script setup>
	import {
		computed,
		onMounted,
		ref
	} from "vue";
	import {
		ImgBaseUrl
	} from "@/utils/domain.js";
	import {
		queryJobDetail,
		card
	} from "@/api/findJob.js";
	import {
		PeopleDetailCollect,
	} from '@/api/findPeople.js'
	import CustomNavBar from "@/components/custom-navbar/index.vue";
	import CallDialog from '@/components/CallDialog.vue'
	import {
		getCityCode,
		getLatitude,
		getLongitude,
		formatDate
	} from "@/common/util.js";
	import {
		getUserEncryption
	} from '@/api/findPeople.js'
	import {
		onLoad,
		onShareAppMessage
	} from '@dcloudio/uni-app';
	import SharePopup from '@/components/SharePopup.vue' // 导入分享组件

	const item1 = ["接单快", "质量高", "态度好"];
	const bgStyle = computed(() => ({
		backgroundImage: `url(${ImgBaseUrl}detail_bg.png)`
	}));
	const detail = ref({});
	const jobId = ref('');
	const currentUserInfo = ref({});
	const showCallDialog = ref(false)
	const phoneNumber = ref(''); // 初始默认号码
	const showMore = ref(false); // 控制是否显示更多
	// 分享相关数据
	const sharePopup = ref(null);
	const shareData = ref({
		title: '',
		path: '',
		imageUrl: ''
	});
	// 坐标数据
	const center = ref({
		latitude: '',
		longitude: ''
	});
	const goBack = () => {
		uni.navigateBack({
			delta: 1
		});
	};

	const sendCard = async () => {
		const res = await card({
			id: jobId.value
		});
		if (res.code === 200) {
			uni.showToast({
				title: '推荐成功',
				icon: 'none'
			})
		}
		// uni.navigateTo({
		//   url: "/pages/chat/detail/index?peerId=" + detail.value.userInfo.id + "&userId=" + currentUserInfo.value.id + "&actionType=card" + "&peerName=" + detail.value.userInfo.userName,
		// });
	}

	const JobDetail = async id => {
		const params = {
			id,
			cityCode: getCityCode(),
			lat: getLatitude(),
			lng: getLongitude()
		};
		const res = await queryJobDetail(params);
		detail.value = res.data;
		console.log(detail.value)
	};
	const displayedRecommendations = computed(() => {
		// 计算需要显示的数据：未展开时最多2条，展开时显示全部
		if (!detail.value?.busServiceResults) return [];
		return showMore.value ?
			detail.value.busServiceResults :
			detail.value.busServiceResults.slice(0, 2);
	});

	// 切换显示更多/收起状态
	const toggleShowMore = () => {
		showMore.value = !showMore.value;
	};
	// 打开分享弹窗
	const shareToggle = () => {
		// 设置分享数据
		shareData.value = {
			title: detail.value?.name || '推荐一位优质服务者',
			path: `/pages/tabBars/findJob/jobDetail?jobId=${detail.value}`,
			imageUrl: detail.value?.imgUrl || `${ImgBaseUrl}banner.png`
		};

		sharePopup.value?.open();
	};
	// 分享弹窗关闭回调
	const handleShareClose = () => {
		console.log('分享弹窗已关闭');
	};
	onShareAppMessage(() => {
		return {
			path: `/pages/tabBars/findJob/jobDetail?jobId=${detail.value}`, // 注意携带必要参数
			title: detail.value?.name || '推荐一位优质服务者', // 动态标题（优先使用服务者名称）
			imageUrl: detail.value?.imgUrl || `${$ImgBaseUrl}banner.png` // 可选：分享卡片图片
		};
	});
	const titleWithDefault = computed(() => ({
		...detail.value.title,
		contact: detail.value.title?.contact ?? false
	}));
	onMounted(async () => {
		const pages = getCurrentPages();
		const currentPage = pages[pages.length - 1];
		const query = currentPage.options;
		jobId.value = query.jobId
		JobDetail(jobId.value);
		const user_info = uni.getStorageSync('user_info');
		if (user_info) {
			currentUserInfo.value = JSON.parse(user_info)
		}
	});
	// 联系雇主
	const contactEmployer = async () => {
		if (currentUserInfo.value.id === detail.value.userInfo.id) {
			uni.showToast({
				title: '不能联系自己哦~',
				icon: 'none'
			})
		} else {
			showCallDialog.value = true
			try {
				const res = await getUserEncryption(detail.value.userInfo.id);
				console.log('获取加密号码接口返回', res);
				if (res.code === 200) {
					phoneNumber.value = res.data
				}
				// 假设接口返回的加密号码字段是 encryptionPhone，根据实际接口调整

			} catch (err) {
				console.error('获取加密号码失败', err);
			}
		}
	}
	// 收藏
	const collectHandle = async (state) => {
		// console.log('state-----', state);
		try {
			const params = {
				collectId: jobId.value,
				collectType: "JOB",
				isCollect: !state.contact
			};

			const res = await PeopleDetailCollect(params);
			if (res.code === 200) {
				state.contact = !state.contact;
				if (detail.value && detail.value.title) {
					detail.value.title.contact = state.contact;
				}
				uni.showToast({
					title: state.contact ? '收藏成功' : '已取消收藏',
					icon: 'none'
				});
			} else {
				uni.showToast({
					title: res.msg || '操作失败',
					icon: 'none'
				});
			}
		} catch (error) {
			console.error('收藏操作失败:', error);
			uni.showToast({
				title: res.msg || '操作失败，请重试',
				icon: 'none'
			});
		}
	};
	// 打开地图导航
	const openMap = () => {
		// 检查是否有经纬度信息
		if (detail.value.serviceInfo.lat && detail.value.serviceInfo.lng) {
			// 使用微信小程序地图接口
			uni.openLocation({
				latitude: Number(detail.value.serviceInfo.lat), // 目标纬度
				longitude: Number(detail.value.serviceInfo.lng), // 目标经度
				// name: item.name, // 位置名称
				address: detail.value.serviceInfo.address, // 详细地址
				scale: 18, // 缩放级别，范围5-18
				success: () => {
					console.log('地图打开成功');
				},
				fail: (err) => {
					console.error('地图打开失败：', err);
					uni.showToast({
						title: '无法打开地图',
						icon: 'none'
					});
				}
			});
		} else {
			// 如果没有经纬度，尝试使用地址解析
			uni.showToast({
				title: '正在解析地址...',
				icon: 'loading'
			});

			// 调用逆地理编码接口（需要后端支持）
			uni.request({
				url: '/api/geo/address-to-coord',
				method: 'GET',
				data: {
					address: item.address
				},
				success: (res) => {
					if (res.data.success && res.data.latitude && res.data.longitude) {
						uni.openLocation({
							latitude: Number(res.data.latitude),
							longitude: Number(res.data.longitude),
							name: item.name,
							address: item.address,
							scale: 18
						});
					} else {
						uni.showToast({
							title: '无法解析该地址',
							icon: 'none'
						});
					}
				},
				fail: () => {
					uni.showToast({
						title: '地址解析失败',
						icon: 'none'
					});
				}
			});
		}
	};
	// 跳转到举报中心
	const goReport = ((detail) => {
		// console.log('detail',detail);
		const detailStr = encodeURIComponent(JSON.stringify(detail));
		uni.navigateTo({
			url: `/pages/reportCenter/report?item=${detailStr}`,
		});
	})
</script>

<style lang="scss" scoped>
	.content {
		position: relative;
		width: 100%;
		height: 100vh;
		box-sizing: border-box;
		// background-image: var(--bg-url);
		// background-size: 100% auto; /* 宽度100%，高度自动 */
		background-repeat: no-repeat;
		background-position: top center;
		/* 关键：图片顶部对齐 */
		overflow: hidden;

		.center {
			width: 100%;
			box-sizing: border-box;
			flex: 1;
			overflow-y: auto;
			padding: 0 24rpx 10rpx;

			// margin-bottom: 100rpx;
			.top {
				background: #FFFFFF;
				border-radius: 20px;
				padding: 43rpx 34rpx 37rpx;
				margin-top: 40rpx;
				margin-bottom: 24rpx;

				.photo {
					width: 100rpx;
					height: 100rpx;
					border-radius: 50%;
					margin-right: 16rpx;
				}

				.title {
					font-weight: 500;
					font-size: 36rpx;
					color: #333333;
				}

				// .icon {
				// 	background: white;
				// 	border-radius: 50%;
				// 	width: 40rpx;
				// 	height: 40rpx;
				// 	margin-left: 20rpx;
				// 	display: inline-flex;
				// 	align-items: center;
				// 	justify-content: center;

				// 	image {
				// 		width: 25rpx;
				// 		height: 25rpx;
				// 		display: block;
				// 	}
				// }





				.box2 {
					display: flex;
					margin-top: 20rpx;

					.item {
						background: #e6f1ff;
						border-radius: 6rpx;
						font-size: 24rpx;
						color: #2f80ed;
						padding: 6rpx 10rpx;
						margin-right: 16rpx;
						font-weight: 500;
					}
				}



			}


			.demand {
				background: white;
				border-radius: 20px;
				padding: 32rpx 34rpx 53rpx;
				margin-bottom: 24rpx;

				.title {
					justify-content: center;
					align-items: center;
					margin-bottom: 6rpx;

					image {
						width: 32rpx;
					}

					text {
						font-weight: 500;
						font-size: 36rpx;
						color: #333333;
						margin: 0 24rpx;
					}
				}



				.job-item {
					background: #F7F7F7;
					padding: 24rpx 23rpx 33rpx;
					border-radius: 16px;
					margin-top: 24rpx;

					.box1 {
						border-bottom: 2px solid #e2e2e2;
						padding-bottom: 20rpx;

						.photo {
							width: 34rpx;
							height: 34rpx;
							border-radius: 50%;
							margin-right: 15rpx;
						}

						.name {
							font-weight: 500;
							font-size: 30rpx;
							color: #333333;
						}


					}
				}

			}

			.demand2 {
				display: flex;

				.avatar-box {
					width: 100rpx;
					height: 100rpx;
					margin-right: 20rpx;

					.photo {
						width: 100%;
						height: 100%;
						border-radius: 50%;
					}
				}

				.demand2-box {
					.name {
						font-weight: 500;
						font-size: 34rpx;
						color: #333;
					}
				}
			}

			.rate {
				margin-top: 10rpx;

				.text1 {
					font-size: 24rpx;
					color: #999999;
				}

				.value1 {
					font-weight: 500;
					font-size: 30rpx;
					color: #feb310;
				}
			}

			.box1 {
				// background: #f0f0f0;
				border-radius: 6rpx;
				padding: 5rpx 30rpx;
				margin-top: 16rpx;

				.text2 {
					font-size: 24rpx;
					color: #666666;
				}

				.value2 {
					font-weight: 500;
					font-size: 24rpx;
					color: #2f80ed;
					margin-left: 16rpx;
				}

				.left {
					margin-left: 40rpx;
				}
			}

			.box3 {
				font-size: 24rpx;
				color: #999999;
				margin-top: 16rpx;

				.detail_browse {
					width: 26rpx;
					height: 17rpx;
				}

				.detail_phone {
					width: 22rpx;
					height: 22rpx;
				}

				image {
					// width: 20rpx;
					margin-right: 8rpx;
				}

				text {
					margin-right: 35rpx;
				}
			}
		}

		.demand_content {
			font-weight: 400;
			font-size: 28rpx;
			color: #333333;
			line-height: 50rpx;
		}

		.footer {
			// position: fixed;
			// bottom: 0;
			// left: 0;
			width: 100%;
			height: 100rpx;
			background: #ffffff;
			display: flex;
			align-items: center;
			padding: 22rpx 0;

			.box3 {
				align-items: center;
				margin: 0 30rpx 0 46rpx;

				.icon {
					width: 36rpx;
				}

				.text1 {
					font-size: 22rpx;
					color: #666666;

					margin-top: 12rpx;
				}
			}

			.btn {
				background: #2f80ed;
				border-radius: 44px;
				height: 88rpx;
				line-height: 88rpx;
				text-align: center;
				margin-left: 22rpx;
				flex: 1;
				margin-right: 22rpx;
				font-weight: 500;
				font-size: 30rpx;
				color: #ffffff;
			}
		}
	}

	.distance {
		display: flex;
		align-items: center;

		image {
			width: 20rpx;
			height: 20rpx;
		}

		.text2 {
			font-size: 24rpx;
			color: #666666;
			margin-left: 7rpx;
		}
	}

	.line2 {
		display: flex;
	}

	.order-map {
		border-radius: 20rpx;
		margin-top: 20rpx;


		.map-container {
			width: 100%;
			// height: 100vh;
		}
	}

	.icon-box {
		width: 80rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;

		.icon {
			width: 25rpx;
			height: 25rpx;
			display: block;
		}

		.icon-box-text {
			font-weight: 400;
			font-size: 24rpx;
			color: #666;
		}

	}

	.icon-box-margin {
		margin-top: 30rpx;

		.icon-content {
			width: 85%;
			display: flex;
			justify-content: space-between;
		}
	}

	.text1 {
		font-size: 30rpx;
		font-weight: 400;
		color: #333;
	}

	.line1 {
		margin-top: 20rpx;
	}

	.line2 {
		margin-top: 20rpx;
	}

	.view-more-btn {
		// width: 100%;
		height: 50rpx;
		line-height: 80rpx;
		text-align: center;
		font-size: 24rpx;
		color: #999;
		font-weight: 500;
		margin-top: 20rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #fff;
		font-weight: 400;
		// border-radius: 16rpx;

		.more-icon {
			margin-left: 10rpx;
		}
	}

	.content-text {
		font-size: 30rpx;
		font-weight: 500;
		color: #333;
		display: -webkit-box;
		/* 弹性盒模型，用于多行文本溢出 */
		-webkit-box-orient: vertical;
		/* 垂直排列 */
		-webkit-line-clamp: 4;
		/* 限制显示3行 */
		overflow: hidden;
		/* 溢出内容隐藏 */
		text-overflow: ellipsis;
		/* 溢出部分显示省略号 */
		word-break: break-all;
	}
</style>